import React, { useState } from 'react';
import { Upload, Button, message, Image } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { upload } from '@/services/ant-design-pro/api';  
import { create } from 'lodash';

const ImageUpload = ({ value, onChange, maxSize = 1, maxWidth = 1024, maxHeight = 1024 }) => {
  const [loading, setLoading] = useState(false);
  const [fileSize, setFileSize] = useState(null);
  const [fileDimensions, setFileDimensions] = useState(null);

  const handleUpload = async (file) => {
    const fileSizeInMB = file.size / (1024 * 1024);
    const isValidSize = fileSizeInMB <= maxSize;
    // const isValidDimensions = file.width <= maxWidth && file.height <= maxHeight;

    if (!isValidSize) {
      message.error(`图片大小不能超过 ${maxSize}MB`);
      return;
    }

    setLoading(true);
    setFileSize(fileSizeInMB.toFixed(2));
    setFileDimensions({ width: file.width, height: file.height });

    try {
      const formData = new FormData();
      formData.append('file', file);
      const response = await upload(formData);
      onChange(response.data[0]); // 假设返回图片的 URL
      message.success('上传成功');
    } catch (error) {
      message.error('上传失败');
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = ({ file }) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const img = document.createElement('img');
      img.src = e.target.result;
      img.onload = () => {
        file.width = img.width;
        file.height = img.height;
        handleUpload(file);
      };
    };
    reader.readAsDataURL(file);
  };

  return (
    <div>
      {value ? (
        <div>
          <Image src={value} width={100} />
          <div>
            {/* <span>大小: {fileSize} MB</span>
            <span>尺寸: {fileDimensions?.width}x{fileDimensions?.height} 像素</span> */}
          </div>
          <Button type="link" onClick={() => onChange('')}>删除</Button>
        </div>
      ) : (
        <Upload
          beforeUpload={() => false} // 阻止自动上传
          onChange={handleFileChange}
        >
          <Button icon={<UploadOutlined />} loading={loading}>
            上传图片
          </Button>
          <div>
            {(maxWidth && maxHeight) && ( <span>推荐尺寸: {maxWidth}x{maxHeight} 像素</span>) }
          </div>
        
        </Upload>
      )}
    </div>
  );
};

export default ImageUpload;